package com.second.oa.service.impl;

import java.sql.SQLException;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import com.second.oa.dao.PowerDao;
import com.second.oa.dao.impl.PowerDaoImpl;
import com.second.oa.domain.Employee;
import com.second.oa.domain.Power;
import com.second.oa.service.PowerService;

public class PowerServiceImpl implements PowerService  {

	private PowerDao powerDao = new PowerDaoImpl();
	
	public Set<Power> getPowerByEmp(Employee emp) throws SQLException {
		
		String sql = "select * from (select * from t_power where power_level = 1 union  select p.* from  t_power p  inner join t_role_power rp on p.id = rp.power_id  inner join t_emp_role er on rp.role_id = er.role_id  where er.emp_id = ?) order by power_level asc";
		
		List<Power> ps = powerDao.list(sql, emp.getId());
		Set<Power> flps = new TreeSet<Power>();
		
		for(Power p : ps) {
			if(p.getPowerLevel() == 1) {
				flps.add(p);
			} else {
				for(Power parentPower : flps) {
					// 如果找到父菜单,则加入到该菜单的子菜单列表中
					if(p.getParent() != null && parentPower.getId().equals(p.getParent().getId())) {
						parentPower.getPowers().add(p);
					}
				}
			}
		}
		
		return flps;
	}

}
